package com.ndhutu.ee.util.ali.sts;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.ali.oss.OSSConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里STS授权管理工具类
 * @Author Shane
 * @Date 2019/9/2 22:19
 */
public class STSUtil {
    /**
     * 获取临时授权凭证
     * @Author Shane
     * @Date 2019/9/311:09
     * @param
     * @return
     **/
    public static Map<String, Object> provisionalAuthority(STSConfig stscConfig, OSSConfig ossConfig) throws Exception{
        // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
        DefaultProfile.addEndpoint("", "", "Sts", stscConfig.getEndpoint());
        // 构造default profile（参数留空，无需添加region ID）
        IClientProfile profile = DefaultProfile.getProfile("", stscConfig.getAccessKeyId(), stscConfig.getAccessKeySecret());
        // 用profile构造client
        DefaultAcsClient client = new DefaultAcsClient(profile);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setMethod(MethodType.POST);
        request.setRoleArn(stscConfig.getRoleArn());
        request.setRoleSessionName(stscConfig.getRoleSessionName());
        // 若policy为空，则用户将获得该角色下所有权限
        request.setPolicy(StringUtil.isEmpty(stscConfig.getPolicy()) == true ? null : stscConfig.getPolicy());
        // 设置凭证有效时间
        request.setDurationSeconds(1000L);
        final AssumeRoleResponse response = client.getAcsResponse(request);

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("expiration", DateUtil.transFormatUTC(response.getCredentials().getExpiration(), "yyyy-MM-dd HH:mm:ss"));
        data.put("accessKeyId", response.getCredentials().getAccessKeyId());
        data.put("accessKeySecret", response.getCredentials().getAccessKeySecret());
        data.put("securityToken", response.getCredentials().getSecurityToken());
        data.put("bucketName", ossConfig.getBucketName());
        data.put("endpoint", ossConfig.getEndpoint());
        return data;
    }

    public static void main(String[] args) throws Exception {
        String endpoint = "sts.aliyuncs.com";
        String accessKeyId = "LTAI4FhCTJbd2621A6wkWRrp";
        String accessKeySecret = "smBSYP1whk8fjKibiWgvRikLSJB64k";
        String roleArn = "acs:ram::1846066963264360:role/ppfriend";
        String roleSessionName = "session-name";
        String policy = null;

//        STSConfig stsConfig = new STSConfig(endpoint, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy);
//        OSSConfig ossConfig = new OSSConfig();
//        provisionalAuthority(stsConfig, ossConfig);
    }
}
